﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;



namespace Command_
{


    public class PushToDBService : ICommand
    {

        public CreateCurrencyResponse CreateCurrency(CreateCurrencyRequest request)
        {
            CreateCurrencyResponse RateResponse = new CreateCurrencyResponse();

            try
            {
                using (ExtRatesEntities context = new ExtRatesEntities())
                {
                    Currency CurrencyTemp = new Currency()
                    {
                        Name = request.Name
                    };
                    context.AddToCurrency(CurrencyTemp);
                    context.SaveChanges();
                }
            }
            catch (Exception e)
            {
                RateResponse.Status = ResponseStatus.Error;
            }

            return RateResponse;
        }

        public CreateRateResponse CreateRate(CreateRateRequest request)
        {
            CreateRateResponse RateResponse = new CreateRateResponse();

            try
            {
                using (ExtRatesEntities context = new ExtRatesEntities())
                {
                    Currency CurrencyTemp = context.Currency.Where(c => c.Name == request.CurrencyName).FirstOrDefault();

                    Period PeriodTemp = context.Period.Where(c => c.DateTime == request.Period).FirstOrDefault();
                    if (PeriodTemp == null)
                    {
                        PeriodTemp = new Period()
                        {
                            DateTime = request.Period
                        };

                        context.AddToPeriod(PeriodTemp);
                        context.SaveChanges();
                    }

                    CurrencyRate CurrencyRateTemp = new CurrencyRate()
                    {
                        Value = request.Value,
                        Period = PeriodTemp,
                        Currency = CurrencyTemp
                    };
                    context.AddToCurrencyRate(CurrencyRateTemp);
                    context.SaveChanges();
                }

                RateResponse.Status = ResponseStatus.OK;
            }
            catch (Exception e)
            {
                RateResponse.Status = ResponseStatus.Error;
            }

            return RateResponse;
        }
        // calculation algorithm.. 
    }



}
